package com.lhoverc.aop;

import com.alibaba.fastjson.JSONObject;
import com.lhoverc.mapper.LogMapper;
import com.lhoverc.pojo.entity.LogEntity;
import com.lhoverc.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @Author: LiCheng
 * @CreateTime: 2025-04-26
 * @Description:
 * @Version: 1.0
 */
@Slf4j
@Component
@Aspect
public class LogAspect {

    @Autowired
    private LogMapper logMapper;
    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.lhoverc.annotation.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //操作人ID --当前登录人Id（获取请求头中的jwt令牌，解析令牌）
        String jwt = request.getHeader("token");
        Claims claims = JwtUtil.parseJWT(jwt);
        Integer operateId = (Integer) claims.get("id");

        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //操作类类名
        String className = joinPoint.getTarget().getClass().getName();

        //操作方法名
        String methodName = joinPoint.getSignature().getName();

        //操作方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        long startTime = System.currentTimeMillis();
        //调用原始目标方法运行
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();

        //方法返回值
        String returnValue = JSONObject.toJSONString(result);

        //操作耗时
        long costTime = endTime - startTime;

        //记录操作日志
        LogEntity logEntity = new LogEntity(null, operateId, operateTime, className, methodName, methodParams, returnValue, costTime, null);
        logMapper.insert(logEntity);

        log.info("AOP记录操作日志：{}", logEntity);
        return result;
    }
}
